Ext.ns('App');

/**
 * Custom class for the put info ex actions. Displays fad record details for updating or display. <br>
 * <b>formContainer</b> field is the formpanel of the panel. This can be gotten by getForm function.
 */
App.SearchFormPopupPanel = Ext.extend(Ext.Panel, {
    map: null,
    floating: true,
    modal: true,
    editable: true,
    //centered: true,
    //width: Ext.is.Phone ? undefined : 400,
    //height: Ext.is.Phone ? undefined : 400,
    scroll: false,
    layout: 'fit',
    //fullscreen: Ext.is.Phone ? true : undefined,
    fullscreen: true,
    errorText: 'Sorry, we had problems communicating with server. Please try again.',
    errorTitle: 'Communication error',
    maxResults: 6,
    featureClass: "P",
    infoDetail: null,
    
    /**
     * When user selects Category, a fad is matched by selected category.
     * @cfg {NG.models.Table} fad
     */
    fad: null,
    
    /**
     * Mandatory field. Possible values are 'insert' or 'update'.
     * @cfg {String} dmlType
     */
	dmlType: null,

	/**
	 * Handles Save button click.
	 * @function doSave
	 */
    doSave: function(){
    	var panel = this;
    	if (this.dmlType === 'update')    	
			Ext.dispatch({
				controller: app.controllers.infoView,
				action: 'updateFAD',
				modifiedFields: this.getForm().getRecord().modifiedFields,
				infoDetail: this.infoDetail,
				formPanel: this,
				callback: {
					successFn: function (){
						panel.formContainer.hideMask();
					},
					failureFn: function (){
						panel.formContainer.hideMask();
					}					
				}
			});
    	else if (this.dmlType === 'insert')    	
			Ext.dispatch({
				controller: app.controllers.infoView,
				action: 'insertFAD',
				modifiedFields: this.getForm().getRecord().modifiedFields,
				fad: this.getFAD(),
				coordinates: this.getForm().getRecord().getCoordinatesString(),
				formPanel: this,
				callback: {
					successFn: function (){
						panel.formContainer.hideMask();
					},
					failureFn: function (){
						panel.formContainer.hideMask();
					}					
				}
				//modifiedFields: this.getForm().getRecord().modifiedFields,
				//infoDetail: this.infoDetail
			});
    },

    
    /**
     * @return {Ext.form.FormPanel} Form panel of the container.
     */
    getForm: function (){
    	return this.formContainer;
    },
    
    /**
     * If insert opertion will be performed fad which matchs by selected category must be set.
     * @return {NG.models.Table}
     */
    getFAD: function (){
    	return this.fad;
    },
    
    initComponent: function(){
    	var formItems = this.formItems;
    	var editable = this.editable;
    	var record = this.record;
        this.formContainer = new Ext.form.FormPanel({
            scroll: true,
            waitTpl: new Ext.XTemplate(WAIT_TPL),
            items: [{
                xtype: 'button',
                cls: 'apply-btn',
                ui: 'confirm-small',
                text: L_SAVE,
                disabled: !editable,
                width: 100,
                handler: function(){
                	this.formContainer.showMask({        
                		message : L_PLEASE_WAIT,
                        transparent : false,
                        target  : this.formContainer,  //optional target Element
                        cls : 'form-mask',
                        customImageUrl : 'img/netcad.png'
                	});
                	this.doSave();
                    //this.hide();
                },
                scope: this 
            },{
                xtype: 'button',
                cls: 'close-btn',
                ui: 'decline-small',
                text: L_CLOSE,
                width: 100,	
                handler: function(){
                	this.hide();
                }
                ,scope: this 
            }, {
                xtype: 'fieldset',
                scroll: false,
                title: L_FILL_CAT_INFO,
                defaults: {
                	listeners: {
                		change: function (comp, newValue, oldValue){
                			var record = comp.ownerCt.ownerCt.getRecord();
                			if (!record)
                				return;
                			record.set(comp.getName(), newValue);
                			record.modifiedFields.add(comp.getName(), newValue);
                		}
                	}                                                	
                },
                items: [formItems]
            }]
        });
        this.items = [{
            xtype: 'panel',
            layout: 'fit',
            items: [this.formContainer]
        }];
        App.SearchFormPopupPanel.superclass.initComponent.call(this);
    }
});


/**
 * //TODO dokümantasyonu sonraya bırak 13.08.2011
 * Used by PutInfoEx
 * @returns formpanel
 */
NG.info = function (params){
	var form;
	
    var formBase = {
        scroll: 'vertical',
        standardSubmit : false,
        items: [{
                xtype: 'fieldset',
                title: 'Bilgiler',
                instructions: 'Seçtiklerinizle ilgili girebilirsiniz',
                defaults: {
                    required: true,
                    useClearIcon: true,
                    labelAlign: 'left',
                    labelWidth: '40%'
                },
                items: []
            }
        ],
        listeners : {
            submit : function(form, result){
                NGLogger.info('success', Ext.toArray(arguments));
            },
            exception : function(form, result){
                NGLogger.info('failure', Ext.toArray(arguments));
            },
            show : function(form) {
            	//TODO gösterildiğinde neler render edilecek
            	//form.loadModel(app.getSettings());
            } 
        },
    
        dockedItems: [
            {
                xtype: 'toolbar',
                dock: 'bottom',
                items: [
					{
						iconCls: 'delete',
						iconMask: true,
						ui: 'plain',
						handler: function (){
							//TODO ipad'de klavye yok olmuyor kapatırken
							form.hide();
						}
					},
					{xtype: 'spacer'},                            
                    {
                        text: 'Temizle',
                        handler: function() {
                            form.reset();
                        }
                    }, {
                        text: L_SAVE,
                        ui: 'confirm',
                        handler: function() {
                        }
                    }
                ]
            }
        ]
    };
    
    /**
     * <b>params</b> param consists of<br>
     * <li>infoDetail: NG.models.InfoDetail. Can be null when a fad is being inserted.
     * <li>editable: Boolean. Form will be editable and postable or readonly
     * <li>insert: Boolean. When an insertion is made, this must be.
     * 
     * @param {Object} params
     */
    this.initForm = function(params) {
    	
    	params = Ext.apply({
    		editable: true,
    		insert: false,
    		selectedFAD: null,
    		sessionID: null,
    		polygon: null
    	}, params);
    	
    	
    	if (params.insert) {
        	return this.showFormForInsert(params.selectedFAD, params.sessionID, params.polygon);
    	} else { //view or update (not insert operation)
    		var formItems = [];
    		var infoDetail = params.infoDetail;
    		if (!infoDetail) {
    			alert("Info Detail must not be null");
    			return formItems;
    		}
    		
    		var record = infoDetail.getRecordForPutInfoEx();
    		var panel = new App.SearchFormPopupPanel({
    			formItems: record.formItems,
    			editable: params.editable,
    			infoDetail: infoDetail,
    			dmlType: 'update'
    		});
    		panel.getForm().load(record);
    		return panel;    		
    	}
    	    	
    };
    
    /**
     * Shows form with fad information. 
     * @param {NG.models.Table} fad
     * @param {String} sessionID
     * @param {Object} polygon 
     */
    this.showFormForInsert = function(fad, sessionID, polygon) {
    	alert(fad.getTableName() + "\n" + polygon.toString());
    	
    	//coordinates'i daha sonra sakla bir şekilde
    	//value'su aşağıda set ediliyor
		var formItems = [{
			xtype: 'textfield',
			name: 'coordinates',
			label: 'Coordinates'
		}
		];
		
		//for creating record for form
   		var modelFieldArray = ['coordinates'];
		
		var fieldList = fad.getFieldList();
		for ( var i = 0; i < fieldList.length; i++) {
			if (fieldList[i].isLookUp() ) { //&& fieldList[i].getFieldName() != "DURUM") {
				//fieldList[i].createComboItemList(options.polygon, component);
			}
			else {
				//continue;
			}
			var field = fieldList[i];
			var component = {
				name: field.getFieldName(),
				label: field.getDisplayName()			
			};
			
			/***test***/
			/*
			if (i == 0) {
				component = new Ext.form.ux.touch.GenericPickerField(Ext.apply(component, {
					label: 'xxx',
					showLoading: true
				}));
				//field.createComboItemList(polygon, component);
			}
			if (i == 14) {
				console.log(field.data.isLookUp);
			}
			*/
			/***!test***/
			

			if (field.isLookUp()) {
				//TODO
				component = new Ext.form.ux.touch.GenericPickerField(Ext.apply(component, {
					showLoading: true
				}));
				field.createComboItemList(polygon, component);
			} else if (field.isStr()) {
				component.xtype = "textfield";
			} else if (field.isInt()) {
				component.xtype = "numberfield";
			} else if (field.isMemo()) {
				component.xtype = "textareafield";
			} else if (field.isDate()) {
				component = new Ext.form.DatePicker(Ext.apply(component, {
					
				}));
			} else if (field.isFloat()) {
				component.xtype = "numberfield";
			} else {
				alert(field.getFieldType() + " --> Field data type is not recognized.");
				continue;
			}
			formItems.push(component);
			modelFieldArray.push(name);

		}
	

    	var panel = new App.SearchFormPopupPanel({
			formItems: formItems,
			editable: true,
			dmlType: 'insert',
			hideOnMaskTap: false,
			modal: true,
			fad: fad
		});
    	
    	//Create record for form
    	Ext.regModel('Putinfoex-Insert-Record', {
    	    fields: modelFieldArray,
    	    modifiedFields: new Ext.util.HashMap(),
    	    formItems: formItems,
    	    phantom: true,
    	    getCoordinatesString: function (){
    	    	return this.data.coordinates;
    	    } 
    	}); 
    	var record = Ext.ModelMgr.create(
    			{
    				coordinates: NG.util.OpenLayerGeometryToCoordinateString(polygon)
    			}, 
    			'Putinfoex-Insert-Record');
    	
		panel.getForm().load(record);
		
    	return panel;
    };
};

/**
 * 
 */
NG.measureInfo = function (htmlContent) {
	var measureInfoPanel = null;
    if (!(measureInfoPanel = Ext.getCmp('measure-result-panel'))) {
        measureInfoPanel = new Ext.Panel({
        	id: 'measure-result-panel',
            floating     : true,
            width        : 250,
            height       : 155,
            centered     : false,
            modal        : false,
            hideOnMaskTap: false,
            html: htmlContent,
            dockedItems: [{
              xtype: 'toolbar',
              dock: 'bottom',
              items: [
				{
					iconCls: 'delete',
					iconMask: true,
					ui: 'plain',
					handler: function (){
						measureInfoPanel.hide();
					}
				}]
            }],
            listeners: {
            	afterrender: function (t) {
            		//t.alignTo(Ext.getCmp('map').el, "b-t");
            		var mapViewSize = app.views.mapView.el.getSize();
            		var x = mapViewSize.width - t.el.getSize().width - (Ext.is.Desktop ? 50 : 60); 
            		var y = mapViewSize.height - t.el.getSize().height - 130;
                    measureInfoPanel.el.setX(x);
                    measureInfoPanel.el.setY(y);
            	}
            }
        });        	
    }	
    return measureInfoPanel;
};
